import axios, { type Method } from "axios";
import { ElMessage } from "element-plus";
import { platformResultName } from "@/enums/platform";
import { Platform } from "@/types/multiStore";

/**
 * 响应体定义
 * 多个axios实例传参
 * 错误处理器
 */
type ResponseData<T = any> = {
  data: { code: string; msg: string; data: T };
};
type NewSuperfluousAxiosparams = Platform | 9090;
const rejectHanle = (error: any) => {
  ElMessage.error("服务错误：" + error?.message || error?.msg);
  throw new Error(error);
};

/**
 * 根据平台枚举值返回 axios请求实例
 * @param PLATFORM 平台值
 * @returns axios 实例
 */
const newSuperfluousAxios = (PLATFORM: NewSuperfluousAxiosparams) => {
  // 模拟，写一个测试
  const Authorizations: Record<NewSuperfluousAxiosparams, string> = {
    0: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiIxMTkyODM0NyIsInJuU3RyIjoiSTRvOEZLZk9iUUk3ZURBcGF3eWJ4WUhhUUFlUGViRmIifQ.VWri7RHZ2BHRt1oG8Dt4v3kYsf3oSaPZZcoEHbINnJg",
    1: "",
    2: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiIxOTQ5OTczNzIiLCJyblN0ciI6IlNXclVFMWFUdk1mTTNOWkdxR05lSkk0Mk0xTGF4OFlCIn0.MytIyr9hMWTd0IctMobfxtBcCizpcQc7mO_C7ocf1qA",
    3: "",
    4: "",
    5: "",
    6: "",
    7: "",
    8: "",
    9: "",
    10: "",
    11: "",
    9090: "",
  };
   //TODO1： 构建 axios 模型
  const proxyBaseUrl = platformResultName[PLATFORM];
  const http = axios.create({
    baseURL: `\\${proxyBaseUrl}`,
    timeout: 10000,
    headers:{Authorization:Authorizations[PLATFORM]}
  });
// TODO2：axios 请求拦截
  http.interceptors.request.use(
    (config) => config, 
    (err) => rejectHanle(err)
  );
// TODO3：axios 响应拦截
  http.interceptors.response.use(
    (res) => {
      if (![0, 200].includes(res.data.code))
        rejectHanle(new Error(res.data.msg)); 
      return res;
    },
    (err) => rejectHanle(err)
  );
  // TODO4：处理 GET
  const request = <T>(method: Method, url: string, submitData?: unknown) => {
    return http.request<T, ResponseData<T>>({
      url,
      method,
      [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
    });
  };
  return request;
};

/**
 @returns 0 - 京东 
 @returns 1 - 拼多多
 @returns 2 - 抖音 
 @returns 3 - 小红书 
 @returns 4 - 1688 
 @returns 5 - 微信小店 
 @returns 6 - 快手      
 @returns 7 - 得物 
 @returns 8 - 淘宝 
 @returns 9 - 当当网 
 @returns 10 -  美团 
 @returns 11 -  新版京东
 */
const superfluous: Record<
  NewSuperfluousAxiosparams,
  ReturnType<typeof newSuperfluousAxios>
> = {
  0: newSuperfluousAxios(0),
  1: newSuperfluousAxios(1),
  2: newSuperfluousAxios(2),
  3: newSuperfluousAxios(3),
  4: newSuperfluousAxios(4),
  5: newSuperfluousAxios(5),
  6: newSuperfluousAxios(6),
  7: newSuperfluousAxios(7),
  8: newSuperfluousAxios(8),
  9: newSuperfluousAxios(9),
  10: newSuperfluousAxios(10),
  11: newSuperfluousAxios(11),
  9090: newSuperfluousAxios(9090),
};
export { superfluous };
